import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/services/open_launcher.dart';

import '../../core/providers/user_provider.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/widgets/loading_widget.dart';

class SignupScreen extends ConsumerStatefulWidget {
  const SignupScreen({super.key});

  @override
  ConsumerState<SignupScreen> createState() => _SignupScreenState();
}

class _SignupScreenState extends ConsumerState<SignupScreen> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  bool _isPasswordHidden = true;
  bool _isConfirmPasswordHidden = true;

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/auth_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: [
          _renderTopBar(),
          [
            SizedBox(height: 40.h),
            _renderBrandLogo(),
            SizedBox(height: 60.h),
            _renderRegistrationForm(),
          ].toColumn().expanded(),
          [
            _renderSignupButton(),
            SizedBox(height: 40.h),
            _renderAgreementText(),
            SizedBox(height: 30.h),
          ].toColumn(),
        ].toColumn().safeArea().paddingHorizontal(24.w),
      ),
    );
  }

  Widget _renderTopBar() {
    return [
      Container(
        width: 30.w,
        height: 30.w,
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.circular(15.r),
        ),
        child:
            Icon(
              Icons.arrow_back_ios_new,
            ).iconSize(16.sp).iconColor(Colors.white).center(),
      ).inkWell(onTap: () => GoRouter.of(context).pop()),
      Text('Register')
          .fontSize(24.sp)
          .fontFamily('PoetsenOne')
          .bold()
          .textColor(Colors.black)
          .textAlignment(TextAlign.center)
          .expanded(),
      SizedBox(width: 30.w),
    ].toRow().padding(left: 0.w, right: 16.w, top: 12.h, bottom: 12.h);
  }

  Widget _renderBrandLogo() {
    return Image.asset(
      'assets/resources/star_icon.png',
      width: 183.w,
      height: 100.h,
      fit: BoxFit.contain,
      errorBuilder: (context, error, stackTrace) {
        return Text('Xcite')
            .fontSize(24.sp)
            .bold()
            .textColor(Colors.white)
            .center()
            .parent(
              ({required Widget child}) => Container(
                width: 100.w,
                height: 100.h,
                decoration: BoxDecoration(
                  color: const Color(0xFF2AB061),
                  borderRadius: BorderRadius.circular(50.r),
                ),
                child: child,
              ),
            );
      },
    );
  }

  Widget _renderRegistrationForm() {
    return [
      _createInputField(
        controller: _usernameController,
        placeholder: 'Enter Your Name',
      ),

      SizedBox(height: 20.h),

      _createPasswordField(
        controller: _passwordController,
        placeholder: 'Input Password',
        isHidden: _isPasswordHidden,
        onToggleVisibility: () {
          setState(() {
            _isPasswordHidden = !_isPasswordHidden;
          });
        },
      ),

      SizedBox(height: 20.h),

      _createPasswordField(
        controller: _confirmPasswordController,
        placeholder: 'Confirm Password',
        isHidden: _isConfirmPasswordHidden,
        onToggleVisibility: () {
          setState(() {
            _isConfirmPasswordHidden = !_isConfirmPasswordHidden;
          });
        },
      ),
    ].toColumn();
  }

  Widget _createInputField({
    required TextEditingController controller,
    required String placeholder,
  }) {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        image: const DecorationImage(
          image: AssetImage('assets/resources/input_bg.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: placeholder,
          hintStyle: TextStyle(color: Colors.grey[600], fontSize: 16.sp),
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 20.w,
            vertical: 16.h,
          ),
        ),
        style: TextStyle(fontSize: 16.sp, color: Colors.black),
      ),
    );
  }

  Widget _createPasswordField({
    required TextEditingController controller,
    required String placeholder,
    required bool isHidden,
    required VoidCallback onToggleVisibility,
  }) {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        image: const DecorationImage(
          image: AssetImage('assets/resources/input_bg.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: TextField(
        controller: controller,
        obscureText: isHidden,
        decoration: InputDecoration(
          hintText: placeholder,
          hintStyle: TextStyle(color: Colors.grey[600], fontSize: 16.sp),
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 20.w,
            vertical: 16.h,
          ),
          suffixIcon: Icon(
            isHidden ? Icons.visibility_off : Icons.visibility,
            color: Colors.grey[600],
            size: 20.sp,
          ).inkWell(onTap: onToggleVisibility),
        ),
        style: TextStyle(fontSize: 16.sp, color: Colors.black),
      ),
    );
  }

  Widget _renderSignupButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        image: const DecorationImage(
          image: AssetImage('assets/resources/register_button.png'),
          fit: BoxFit.fill,
        ),
      ),
    ).inkWell(onTap: _executeRegistration);
  }

  Widget _renderAgreementText() {
    return RichText(
      textAlign: TextAlign.center,
      text: TextSpan(
        style: TextStyle(
          fontSize: 12.sp,
          color: Colors.white.withValues(alpha: 0.8),
        ),
        children: [
          const TextSpan(text: 'By Continuing you agree with '),
          TextSpan(
            text: 'Terms of Service',
            style: const TextStyle(
              decoration: TextDecoration.underline,
              color: Colors.white,
            ),
            recognizer:
                TapGestureRecognizer()
                  ..onTap = () {
                    Open.openLaunch(
                      'https://www.freeprivacypolicy.com/live/7ce39277-9d4b-46e1-a768-096bf2f6d765',
                    );
                  },
          ),
          const TextSpan(text: ' & '),
          TextSpan(
            text: 'Privacy Policy',
            style: const TextStyle(
              decoration: TextDecoration.underline,
              color: Colors.white,
            ),
            recognizer:
                TapGestureRecognizer()
                  ..onTap = () {
                    Open.openLaunch(
                      'https://www.freeprivacypolicy.com/live/9c658f5d-4d8a-440f-9dca-6da06109b53d',
                    );
                  },
          ),
        ],
      ),
    );
  }

  /// 执行注册逻辑
  Future<void> _executeRegistration() async {
    if (_usernameController.text.trim().isEmpty) {
      ToastHelper.warning('Please enter your name', context: context);
      return;
    }

    if (_passwordController.text.trim().isEmpty) {
      ToastHelper.warning('Please enter your password', context: context);
      return;
    }

    if (_confirmPasswordController.text.trim().isEmpty) {
      ToastHelper.warning('Please confirm your password', context: context);
      return;
    }

    if (_passwordController.text != _confirmPasswordController.text) {
      ToastHelper.error('Passwords do not match', context: context);
      return;
    }

    // 显示全屏加载
    LoadingWidget.showFullScreen(context, message: 'Registering...');

    try {
      // 调用注册方法
      final success = await ref
          .read(userProvider.notifier)
          .register(
            account: _usernameController.text.trim(),
            password: _passwordController.text.trim(),
            username: _usernameController.text.trim(),
          );

      // 关闭加载
      if (mounted) {
        LoadingWidget.hide(context);
      }

      if (mounted) {
        if (success) {
          ToastHelper.success('Registration successful!', context: context);

          // 跳转到登录页面
          Future.delayed(const Duration(milliseconds: 1000), () {
            if (mounted) {
              context.go('/login');
            }
          });
        } else {
          // 检查是否是账号已存在的问题
          final isAccountExists = ref
              .read(userProvider.notifier)
              .isAccountExists(_usernameController.text.trim());
          if (isAccountExists) {
            ToastHelper.error(
              'Account already exists. Please use a different account.',
              context: context,
            );
          } else {
            ToastHelper.error(
              'Registration failed. Please try again.',
              context: context,
            );
          }
        }
      }
    } catch (e) {
      // 关闭加载
      if (mounted) {
        LoadingWidget.hide(context);
        ToastHelper.error(
          'Registration error: ${e.toString()}',
          context: context,
        );
      }
    }
  }
}
